package com.rykj.energy.task.message.mq.rocketMQ;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@Lazy
public class RocketMQProductClient{

    private String namesrvAddr = "10.152.44.31:9876";
    private String TOPIC_TEST = "topic-alarm";

    public void sendMessage(String topic,String data) {
        Message message = null;
        DefaultMQProducer producer = null;
        try {
            producer = new DefaultMQProducer("ProducerTest");
            producer.setNamesrvAddr(namesrvAddr);
            producer.start();
            //转换成字符数组
            byte[] messageBody = data.getBytes(RemotingHelper.DEFAULT_CHARSET);
            //创建消息对象
            message = new Message(TOPIC_TEST, String.valueOf(System.currentTimeMillis()), messageBody);
            //同步发送消息
            producer.send(message);
            log.info("rocketMQ消息发送成功[{}]",data);
        } catch (Exception e) {
            log.error("rocketMQ消息发送失败",e);
        }finally {
            if (producer != null) {
                producer.shutdown();
            }
        }
    }
}